<?php

namespace app\admin\controller\wx;

use app\common\controller\Backend;
use think\Db;

/**
 * 产品整理
 *
 * @icon fa fa-circle-o
 */
class Protest extends Backend
{
    
    /**
     * Protest模型对象
     * @var \app\admin\model\Protest
     */
    protected $model = null;
    protected $modelPro = null;
    protected $modelProduct = null;
    protected $searchFields = 'id,name';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Protest;
        $this->modelPro = new \app\admin\model\Wxpro();
        $this->modelProduct = new \app\admin\model\Wxproduct();


    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    public function import()
    {
        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        $PHPReader = new \PHPExcel_Reader_Excel2007();
        if (!$PHPReader->canRead($filePath)) {
            $PHPReader = new \PHPExcel_Reader_Excel5();
            if (!$PHPReader->canRead($filePath)) {
                $PHPReader = new \PHPExcel_Reader_CSV();
                if (!$PHPReader->canRead($filePath)) {
                    $this->error(__('Unknown data format'));
                }
            }
        }
        $fieldArr = [
            '上架名称'=>'name',
            '版本'=>'bb',
            '学科'=>'xk',
            '介质'=>'jz',
            '上架价格'=>'sj',
            '定价'=>'dj',
            '备注'=>'bz',
        ];
        $PHPExcel = $PHPReader->load($filePath); //加载文件
        $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
        $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
        $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
        $maxColumnNumber = \PHPExcel_Cell::columnIndexFromString($allColumn);
        for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
            for ($currentColumn = 0; $currentColumn < $maxColumnNumber; $currentColumn++) {
                $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                $fields[] = $val;
            }
        }
        $insert = [];
        for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
            $values = [];
            for ($currentColumn = 0; $currentColumn < $maxColumnNumber; $currentColumn++) {
                $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                $values[] = is_null($val) ? '' : $val;
            }
            $row = [];
            $temp = array_combine($fields, $values);
            foreach ($temp as $k => $v) {
                if (isset($fieldArr[$k]) && $k !== '') {
                    $row[$fieldArr[$k]] = $v;
                }
            }
            if ($row) {
                $insert[] = $row;
            }
        }
        $data = [];
        foreach ($insert as &$value)
        {
            $value['bb'] = explode("\n", $value['bb']);
            $value['xk'] = explode("\n", $value['xk']);
            $value['jz'] = explode("\n", $value['jz']);
            foreach ($value['jz'] as $key=>$jz)
            {
                foreach ($value['xk'] as $xk)
                {
                    foreach ($value['bb'] as $bb)
                    {
                        $data[] = [
                            'name'=>$value['name'],
                            'bb'=>$bb,
                            'xk'=>$xk,
                            'jz'=>$jz,
                            'dj'=>$value['dj']
                        ];
                    }
                }
            }
        }
        if (!$data) {
            $this->error(__('No rows were updated'));
        }
        try {
            $this->model->saveAll($data);
        } catch (\think\exception\PDOException $exception) {
            $this->error($exception->getMessage());
        }

        $this->success();
    }

    public function multi($ids= null)
    {
        $params = $this->request->request('params');
        $data = [];
        //成品
        if($params == 1)
        {
            $list = collection($this->model->where('id','in',$ids)->select())->toArray();
            foreach ($list as $item)
            {
                $data[] = [
                    'name'=>$item['bb'].$item['xk'].$item['jz'],
                    'code'=>$item['code'] ? $item['code']:'',
                    'kg'=>$item['bz'] ? $item['bz']:'',
                    'ministrial'=>$item['dj']? $item['dj']:'',
                    'unit'=>1,
                ];
            }
            $model = $this->modelProduct;

        }
        //半成品
        if($params == 2)
        {
            $list = collection($this->model->where('id','in',$ids)->select())->toArray();
            foreach ($list as $item)
            {
                $data[] = [
                  'name'=>$item['bb'].$item['xk'].$item['jz'],
                  'code'=>$item['code'] ? $item['code']:'',
                  'kg'=>$item['bz'] ? $item['bz']:'',
                ];
            }
            $model = $this->modelPro;
        }
        if (!$data) {
            $this->error(__('No rows were updated'));
        }
        try {
            $model->saveAll($data);
            $this->success();
        } catch (\think\exception\PDOException $exception) {
            $this->error($exception->getMessage());
        }
    }

    public function dels()
    {
        //截断表
        db()->query("TRUNCATE TABLE `hdyj_protest`");
        return $this->success();
    }
}
